package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.applyLeave.applyLeaveResponse;
import com.clouddot.baipai.model.beam.getLeaveRecode.LeaveInfo;
import com.clouddot.baipai.model.beam.getLeaveRecode.getLeaveRecordResponse;
import com.clouddot.baipai.model.beam.getLeaveType.LeaveTypeInfo;
import com.clouddot.baipai.model.beam.getLeaveType.getLeaveTypeResponse;
import com.clouddot.baipai.model.beam.getPersonInfo.getPersonInfoResponse;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.adapter.H_Adapter.leaveRecordRecyclerAdapter;
import com.clouddot.baipai.ui.adapter.H_Adapter.spinnerAdapter;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_MineFragment extends BaseFragment {

    private View view;
    private Context context;

    private LinearLayout data;
    private RelativeLayout scanCard;
    private ImageView imageView;
    private TextView name,className,tel,email  ,sex;
    private leaveRecordRecyclerAdapter adapter;
    private LinearLayout btnLeave ,btngetLeaveReacode;
    private LinearLayout leave,leaveRecode;
    private Button select_endTime,select_startTime;
    private Spinner spinner;
    private LinearLayout btnapply;
    private EditText reasle;
    long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int CurrentPage = 1;
    private int pageCount;
    private LinearLayout last,next;
    private RecyclerView recyclerView;
    private List<LeaveInfo> list = new ArrayList<>();
    private spinnerAdapter spinnerAdapter;
    private String selectIndex;
    private String selectIndexText;
    public List<LeaveTypeInfo> LeaveTypeInfolist = new ArrayList<LeaveTypeInfo>();
    private LinearLayout[] linearLayouts = new LinearLayout[2];
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_minefg,null);

    }

    @Override
    protected void initControls() {
        super.initControls();
        scanCard = view.findViewById(R.id.scanCard);
        data = view.findViewById(R.id.data);
        name = view.findViewById(R.id.name);
        className = view.findViewById(R.id.className);
        sex = view.findViewById(R.id.sex);
        tel = view.findViewById(R.id.tel);
        email = view.findViewById(R.id.emal);
        imageView = view.findViewById(R.id.image);
        data.startAnimation(animation3);
        btnLeave = view.findViewById(R.id.getleavebtn);
        btngetLeaveReacode = view.findViewById(R.id.leaveRecordbtn);
        linearLayouts[1] = btnLeave;
        linearLayouts[0] = btngetLeaveReacode;

        leave = view.findViewById(R.id.getleave);
        leaveRecode = view.findViewById(R.id.leaveRecord);
        select_endTime = view.findViewById(R.id.select_endTime);
        select_startTime = view.findViewById(R.id.select_startTime);
        spinner = view.findViewById(R.id.spinner);
        btnapply = view.findViewById(R.id.apply);
        reasle = view.findViewById(R.id.reasle);
        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);
        recyclerView = view.findViewById(R.id.recycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[0]);
    }

    private TimePickerDialog mDialogYearMonthDay;
    @Override
    protected void setListener() {
        super.setListener();
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);

        btnLeave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                leave.setVisibility(View.VISIBLE);
                leaveRecode.setVisibility(View.GONE);
                runThreadAction("getLeaveType");
                SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[1]);

            }
        });
        btngetLeaveReacode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                leave.setVisibility(View.GONE);
                leaveRecode.setVisibility(View.VISIBLE);
                runThreadAction("getLeaveRecord");
                SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[0]);

            }
        });
        select_startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    selectTime(select_startTime);
            }

        });
        select_endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view){
                    selectTime(select_endTime);
            }

        });

        btnapply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (select_startTime.getText().toString().isEmpty() || select_endTime.getText().toString().isEmpty()){
                    ToastUtil.showToast(context,"必须选择开始时间和结束时间");
                    return;
                }
                if (TextUtils.isEmpty(selectIndex) || TextUtils.isEmpty(selectIndexText)) return ;
                runThreadAction("applyLeave");
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectIndex = LeaveTypeInfolist.get(position).getDimKey();
                selectIndexText = LeaveTypeInfolist.get(position).getDimValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
//
//        Env.getAppPresenter().tasksRepository.setWeiXinResult(new TasksRepository.postWeiXinResult() {
//            @Override
//            public void success(WeiChatNewsResponse response) {
//                if (response.isSuccess()){
//
//                }else{
//
//                }
//
//            }
//
//            @Override
//            public void failure(WeiChatNewsResponse response) {
//            }
//        });


    }


    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
            if (Env.getAppContext().StudentId != null) {
                data.setVisibility(View.VISIBLE);
                scanCard.setVisibility(View.GONE);

                runThreadAction("getPersonInfo");
                runThreadAction("getLeaveRecord");
            } else {
                data.setVisibility(View.GONE);
                scanCard.setVisibility(View.VISIBLE);
                scanCard.startAnimation(animation3);
            }
        }
    }

    @Override
    public void runThreadAction() {
        super.runThreadAction();
    }

    @Override
    protected Object runThreadActionExceute() {
        return super.runThreadActionExceute();
    }

    @Override
    protected void runThreadActionSuccess(Object result) {
        super.runThreadActionSuccess(result);

    }

    @Override
    protected void runThreadActionError(Exception ex) {
        super.runThreadActionError(ex);
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);

        if (actionName.equals("getPersonInfo")) {
           return Env.getAppPresenter().getPersonInfo();
        }else if (actionName.equals("getLeaveType")){
            return Env.getAppPresenter().getLeaveType("1");
        }else if (actionName.equals("getLeaveRecord")){
            return Env.getAppPresenter().getLeaveRecord(CurrentPage,9);
        }else if (actionName.equals("applyLeave")){
            return Env.getAppPresenter().applyLeave(selectIndex,selectIndexText,select_startTime.getText().toString(),select_endTime.getText().toString(),reasle.getText().toString());
        }else if (actionName.equals("WeiChatNews")) {
            return Env.getAppPresenter().WeiChatNews(Env.getAppContext().cardID,selectIndexText,select_startTime.getText().toString(),select_endTime.getText().toString(),reasle.getText().toString());
        }else {

            return null;
        }
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if (actionName.equals("getPersonInfo")) {
            getPersonInfoResponse response = (getPersonInfoResponse) result;
            if(response.isSuccess()){
                Glide.with(context).load(Env.getAppContext().IP+response.Photo)
                        .placeholder(R.drawable.imageload).error(R.drawable.img_02).into(imageView);
                name.setText(response.RealName);
                className.setText("班级：" +response.ClassName);
                sex.setText("性别："+response.Sex);
                tel.setText("电话："+response.Mobile);
                email.setText("邮箱："+response.Email);
            }else{
                ToastUtil.showToast(context,"个人信息获取失败");
            }
        }else if (actionName.equals("getLeaveType")){
            getLeaveTypeResponse response = (getLeaveTypeResponse) result;
            if(response.isSuccess()){
                if (!response.list.isEmpty()){
                    spinnerAdapter = new spinnerAdapter(context);
                    spinnerAdapter.setDatas(response.list);
                    spinner.setAdapter(spinnerAdapter);
                    LeaveTypeInfolist = response.list;
                    selectIndex = response.list.get(0).getDimKey();
                    selectIndexText = response.list.get(0).getDimValue();
                }
            }else{
                ToastUtil.showToast(context,"请假类型获取失败");
            }

        }else if (actionName.equals("getLeaveRecord")){
            getLeaveRecordResponse response = (getLeaveRecordResponse) result;
            if(response.isSuccess()){
                if(!response.list.isEmpty()){
                    list = response.list;
                    pageCount = Integer.parseInt(response.PageCount);
                }
                adapter = new leaveRecordRecyclerAdapter(context ,list);
                recyclerView.setAdapter(adapter);
            }else{
                ToastUtil.showToast(context,"请假记录获取失败");
            }
        }else if(actionName.equals("applyLeave")){
            applyLeaveResponse response = (applyLeaveResponse) result;
            if(response.isSuccess()) {
                ToastUtil.showToast(context,"请假申请已提交成功，请等待老师的审核！");
                runThreadAction("WeiChatNews");
            }else{
                ToastUtil.showToast(context,"请假申请已提交失败，请重新申请");
            }

        }

    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    private void selectTime(final Button btn) {
        mDialogYearMonthDay = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        btn.setText(text);
                    }
                })
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("请选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.colorAccent))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.gray))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.red))
                .setWheelItemTextSize(22)
                .build();

        mDialogYearMonthDay.show(getActivity().getSupportFragmentManager(),"date");
    }

    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;


            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }

            CurrentPage--;
            runThreadAction("getLeaveRecord");
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }

            CurrentPage++;
            runThreadAction("getLeaveRecord");
        }
    };

}
